from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status, views
from rest_framework.decorators import action
from rest_framework.response import Response

from ERP_5.utils.cont import NumberPrefix
from ERP_5.utils.generate_code import generate_code
from erp_system.models import UserModel


class MultipleDestroyMixin:
    """
    自定义，批量删除的视图函数
    """

    del_ids = openapi.Schema(type=openapi.TYPE_OBJECT, required=['ids'], properties={
        'ids': openapi.Schema(type=openapi.TYPE_ARRAY, items=openapi.Schema(type=openapi.TYPE_INTEGER),
                              description="选择哪些需要删除的ID（主键）列表")
    })

    @swagger_auto_schema(method='delete', request_body=del_ids, operation_description="批量删除")
    @action(methods=['delete'], detail=False)
    def multiple_delete(self, request, *args, **kwargs):
        delete_ids = request.data.get('ids')
        if not delete_ids:
            return Response(data={'detail': '参数错误,ids为必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if not isinstance(delete_ids, list):
            return Response(data={'detail': 'ids格式错误,必须为List'}, status=status.HTTP_400_BAD_REQUEST)
        queryset = self.get_queryset()
        del_queryset = queryset.filter(id__in=delete_ids)
        if len(delete_ids) != del_queryset.count():
            return Response(data={'detail': '删除数据不存在'}, status=status.HTTP_400_BAD_REQUEST)
        del_queryset.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


class MultipleOpenMixin:
    """
    自定义，批量启用或者禁用的视图函数
    """

    del_ids = openapi.Schema(type=openapi.TYPE_OBJECT, required=['ids'], properties={
        'ids': openapi.Schema(type=openapi.TYPE_ARRAY, items=openapi.Schema(type=openapi.TYPE_INTEGER),
                              description="选择哪些批量处理的ID（主键）列表"),
        'is_open': openapi.Schema(type=openapi.TYPE_STRING, description="是否启用，启用：0，禁用：1")
    })

    @swagger_auto_schema(method='delete', request_body=del_ids, operation_description="批量启用或者禁用")
    @action(methods=['delete'], detail=False)
    def multiple_open(self, request, *args, **kwargs):
        delete_ids = request.data.get('ids')
        is_open = request.data.get('is_open')  # 是否启用，启用表示：0，禁用表示:1。
        if not delete_ids:
            return Response(data={'detail': '参数错误,ids为必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if not isinstance(delete_ids, list):
            return Response(data={'detail': 'ids格式错误,必须为List'}, status=status.HTTP_400_BAD_REQUEST)
        queryset = self.get_queryset()
        del_queryset = queryset.filter(id__in=delete_ids)
        if len(delete_ids) != del_queryset.count():
            return Response(data={'detail': '传入数据不存在'}, status=status.HTTP_400_BAD_REQUEST)
        del_queryset.update(delete_flag=is_open)
        return Response(status=status.HTTP_204_NO_CONTENT)


# 生成各种编号的接口
class GenerateCode(views.APIView):
    query_param = openapi.Parameter(name='prefix', in_=openapi.IN_QUERY,
                                    description="批号的前缀参考cont.py", type=openapi.TYPE_STRING)

    @swagger_auto_schema(manual_parameters=[query_param])
    def get(self, request, *args, **kwargs):
        """
        生成各种编号的接口，必须传一个前缀: /api/generate_code/prefix=ord，可以参考cont.py

        返回一个28位的编号字符串, return： code就是生成的编号
        """
        prefix = request.query_params.get('prefix', None)
        if prefix:
            if prefix in NumberPrefix.__members__:
                code = generate_code(NumberPrefix[prefix].value)
                return Response(data={'code': code}, status=status.HTTP_200_OK)
            else:
                return Response(data={'detail': 'prefix没有配置，参考cont.py'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(data={'detail': 'prefix没有，该参数必须传'}, status=status.HTTP_400_BAD_REQUEST)


class MultipleAuditMixin:
    """
    自定义的 批量审核(反审核)的 视图函数
    """

    body_param = openapi.Schema(type=openapi.TYPE_OBJECT, required=['ids', 'user_id'], properties={
        'ids': openapi.Schema(type=openapi.TYPE_ARRAY, items=openapi.Schema(type=openapi.TYPE_INTEGER),
                              description="选择哪些需要批量的ID（主键）列表"),
        'user_id': openapi.Schema(type=openapi.TYPE_INTEGER, description="审核人的用户ID"),
        'is_audit': openapi.Schema(type=openapi.TYPE_STRING, description="是否审核，审核：1, 反审核：0")
    })

    @swagger_auto_schema(method='put', request_body=body_param, operation_description="批量审核或者 反审核")
    @action(methods=['put'], detail=False)
    def multiple_audit(self, request, *args, **kwargs):
        audit_ids = request.data.get('ids')
        user_id = request.data.get('user_id')  # 用户ID
        is_audit = request.data.get('is_audit', '1')  # 是否审核，审核：1， 反审核：0

        if not audit_ids:
            return Response(data={'detail': '参数错误,ids为必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if not isinstance(audit_ids, list):
            return Response(data={'detail': 'ids格式错误,必须为List'}, status=status.HTTP_400_BAD_REQUEST)
        queryset = self.get_queryset()
        del_queryset = queryset.filter(id__in=audit_ids)
        if len(audit_ids) != del_queryset.count():
            return Response(data={'detail': '数据不存在'}, status=status.HTTP_400_BAD_REQUEST)
        for item in del_queryset.all():
            if item.status != '1' and is_audit == '0':  # 1以后的状态是不能反审核的
                return Response(data={'detail': '不能反审核，因为订单已生效'}, status=status.HTTP_400_BAD_REQUEST)
            if item.status != '0' and is_audit == '1':  # 0以后的状态是不能审核的
                return Response(data={'detail': '不能审核，因为订单已生效'}, status=status.HTTP_400_BAD_REQUEST)


        if not user_id:
            return Response(data={'detail': '参数错误,user_id为必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        check_user = UserModel.objects.get(id=int(user_id))

        del_queryset.update(status=is_audit, check_user_name=check_user.real_name, check_user_id=check_user.id)
        return Response(status=status.HTTP_200_OK)